<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>修改商品</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <script src="/houtai/js/vue.js"></script>
    <script type="text/javascript" src="/houtai/js/jquery-2.1.4.js"></script>

    <link rel="stylesheet" href="/houtai/layuiadmin/layui/css/layui.css"  media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->


</head>
<body>
<div id="content">
    <form class="layui-form layui-form-pane" id="updateForm">
        <input :value="product.productId" id="productId" name="productId" hidden>
        <input :value="product.businessId" id="businessId" name="businessId" hidden>
        <input :value="product.productCode" id="productCode" name="productCode" hidden>
        <input :value="product.productSales" id="productSales" name="productSales" hidden>
        <input :value="product.productImg" id="productImg" name="productImg" hidden>
        <div class="layui-form-item" style="margin:20px auto;width: 70%">
            <label class="layui-form-label">商品名称</label>
            <div class="layui-input-block">
                <input type="text" name="productName" id="productName" lay-verify="notNull" :value="product.productName" autocomplete="off" placeholder="请输入商品名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-form-text" style="margin:20px auto;width: 70%">
            <label class="layui-form-label">商品描述</label>
            <div class="layui-input-block">
                <textarea name="productDesc" id="productDesc" lay-verify="notNull" :value="product.productDesc" placeholder="请输入商品描述" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item" style="margin:20px auto;width: 70%">
            <div class="layui-inline" style="width: 350px">
                <label class="layui-form-label">商品原价</label>
                <div class="layui-input-block">
                    <input type="text" name="productPrice" id="productPrice" :value="product.productPrice" lay-verify="price" autocomplete="off" placeholder="最多保留2位小数" class="layui-input">
                </div>
            </div>
            <div class="layui-inline" style="margin-left: 30px;width: 350px">
                <label class="layui-form-label">促销价格</label>
                <div class="layui-input-block">
                    <input type="text" name="promotionPrice" id="promotionPrice" :value="product.promotionPrice" lay-verify="price" autocomplete="off" placeholder="最多保留2位小数" class="layui-input">
                </div>
            </div>
        </div>

        <div class="layui-form-item"  style="margin:20px auto;width: 70%">
            <div class="layui-inline" style="width: 350px">
                <label class="layui-form-label">商品类别</label>
                <div class="layui-input-block">
                    <select name="productType" id="productType" v-model="product.productType">
                    </select>
                </div>
            </div>
            <div class="layui-inline" style="margin-left: 30px;width: 350px">
                <label class="layui-form-label">商品库存</label>
                <div class="layui-input-block">
                    <input type="text" name="productNum" id="productNum" :value="product.productNum" lay-verify="num" autocomplete="off" placeholder="只能是正整数" class="layui-input">
                </div>
            </div>
        </div>


<!--        <div class="layui-form-item"  style="margin:20px auto;width: 70%">-->
<!--            <label class="layui-form-label">商品状态</label>-->
<!--            <div class="layui-input-block">-->
<!--                <select name="productStatus" id="productStatus" v-model="product.productStatus">-->
<!--                    <option value="1">上架</option>-->
<!--                    <option value="0">下架</option>-->
<!--                </select>-->
<!--            </div>-->
<!--        </div>-->
<!--        <div class="layui-form-item" style="margin:20px auto;width: 70%">-->
<!--            <label class="layui-form-label">是否热卖</label>-->
<!--            <div class="layui-input-block">-->
<!--                <input type="radio" name="productIshot" value="0" title="是" :checked="product.productIshot">-->
<!--                <input type="radio" name="productIshot" value="1" title="否" :checked="product.productIshot">-->
<!--            </div>-->
<!--        </div>-->

        <div class="layui-form-item"  style="margin:20px auto;width: 70%">
            <div class="layui-inline" style="width: 350px">
                <label class="layui-form-label">商品状态</label>
<!--                <div class="layui-input-block">-->
<!--                    <select name="productStatus" id="productStatus" v-model="product.productStatus">-->
<!--                        <option value="1">上架</option>-->
<!--                        <option value="0">下架</option>-->
<!--                    </select>-->
<!--                </div>-->
                <div class="layui-input-block">
                    <input type="radio" name="productStatus" value="1" v-model="product.productStatus" title="上架">
                    <input type="radio" name="productStatus" value="0" v-model="product.productStatus" title="下架">
                </div>
            </div>
            <div class="layui-inline" style="margin-left: 30px;width: 350px">
                <label class="layui-form-label">是否热卖</label>
                <div class="layui-input-block">
                    <input type="radio" name="productIshot" value="0" v-model="product.productIshot" title="是">
                    <input type="radio" name="productIshot" value="1" v-model="product.productIshot" title="否">
                </div>
            </div>
        </div>

        <div class="layui-upload" style="margin: 20px auto;width: 70%">
            <button type="button" class="layui-btn" id="test1">商品展示图</button><br>
            <span style="color: red">推荐尺寸：500(像素) x 500(像素)</span><br>
            <span style="color: red">注意事项：</span><br>
            <span style="color: red">图片选择完毕后必须点击下方"确认展示图"按钮，不然无法更新</span><br>
            <input type="button" class="layui-btn layui-btn-warm" id="upload" lay-submit value="确认展示图">
            <div class="layui-upload-list" style="border: 1px dashed red;width: 200px;height: 200px">
                <img class="layui-upload-img" id="demo1" :src=product.productImg style="width: 200px;height: 200px">
            </div>
        </div>

        <div class="layui-upload" style="margin: 40px auto;width: 70%">
            <button type="button" class="layui-btn" id="test2">商品轮播图</button><br>
            <span style="color: red">推荐尺寸：500(像素) x 500(像素)</span><br>
            <span style="color: red">轮播图注意事项：</span><br>
            <span style="color: red">1、待上传图片的命名规则：数字+后缀名。例如：1.jpg/2.png,系统会自动根据图片名称进行排序，数字越大，显示越靠前</span><br>
            <span style="color: red">2、点击"商品轮播图"按钮选择需要上传的轮播图，一次可以选择一张或多张</span><br>
            <span style="color: red">3、如果某张图片选择错误，预览区域点击错误图片即可删除</span><br>
            <span style="color: red">4、此次上传会覆盖掉之前的所有图片，如果此次更新需要保留之前的轮播图，此次请把之前的轮播图一并上传</span><br>
            <span style="color: red">5、图片选择完毕后点击下方"确认轮播图"按钮，不然轮播图无法更新</span><br>
            <input type="button" class="layui-btn layui-btn-warm" id="uploadHead" lay-submit value="确认轮播图">
            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                预览图：
                <div class="layui-upload-list" id="demo2"></div>
                <div id="head_img_prev"></div>
            </blockquote>
        </div>
        <div class="layui-upload" style="margin: 40px auto;width: 70%">
            <button type="button" class="layui-btn" id="test3">商品详情图</button><br>
            <span style="color: red">推荐尺寸：500(像素) x 500(像素)</span><br>
            <span style="color: red">商品详情图注意事项：</span><br>
            <span style="color: red">1、待上传图片的命名规则：数字+后缀名。例如：1.jpg/2.png,系统会自动根据图片名称进行排序，数字越大，显示越靠前</span><br>
            <span style="color: red">2、点击"商品详情图"按钮选择需要上传的详情图，一次可以选择一张或多张</span><br>
            <span style="color: red">3、如果某张图片选择错误，预览区域点击错误图片即可删除</span><br>
            <span style="color: red">4、此次上传会覆盖掉之前的所有图片，如果此次更新需要保留之前的详情图，此次请把之前的详情图一并上传</span><br>
            <span style="color: red">5、图片选择完毕后点击下方"确认详情图"按钮，不然详情图无法更新</span><br>
            <input type="button" class="layui-btn layui-btn-warm" id="uploadDetail" lay-submit value="确认详情图">
            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                预览图：
                <div class="layui-upload-list" id="demo3"></div>
                <div id="head_img_detail"></div>
            </blockquote>
        </div>

        <div class="layui-form-item" style="margin: 20px auto;width: 70%">
            <div class="layui-input-block" style="margin-left: 350px" id="submitDiv">
                <input type="button" class="layui-btn" lay-submit lay-filter="updateSubmit" value="立即提交">
            </div>
        </div>
    </form>

</div>



<script src="/houtai/layuiadmin/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->

<script>
    //多图容器 【注册全局变量】
    var multiple_images = [];
    //用于存放商品轮播图对象
    var productImgHeads = [];
    //用于存放商品详情图对象
    var productImgDetails = [];
    //商品ID用于给商品对象赋值
    var productId;
    //判断更改后是否点击确定
    var checkProductIsSure = false;
    var checkHeadIsSure = false;
    var checkDetailIsSure = false;
    //判断是否更改了商品展示图
    var isChangeProductImg = false;
    var isChangeHead = false;
    var isChangeDetail = false;
    //判断是否是第一次上传，第一次上传就清空数组
    var isFirstHead = 1;
    var isFirstDetail = 1;

    //利用Vue钩子函数给表单赋初始值
    var vue = new Vue({
        el:"#content",
        data:{
            product:{},
            allBusiness:[],
            allProTypes:[]
        },
        //获取所有商家，用于商家下拉列表渲染
        beforeCreate:function(){
            var _this = this;
            $.ajax({
                url : "/houtai/page/products/product/getAllBusiness",
                type : "get",
                dataType : "json",
                async: false,
                success : function(data) {
                    _this.allBusiness = data.li;
                    for (var i=0;i<data.li.length;i++ ) {
                        $("#businessId").append("<option  value="+data.li[i].businessId+">"+data.li[i].businessName+"</option>");
                    }
                }
            });
            //获取所有商品类别
            $.ajax({
                url : "/houtai/page/products/product/getAllProTypes",
                type : "get",
                dataType : "json",
                async: false,
                success : function(data) {
                    for (var i=0;i<data.li.length;i++ ) {
                        $("#productType").append("<option  value="+data.li[i].producttypeId+">"+data.li[i].producttypeName+"</option>");
                    };
                }
            });
        },
        //给表单赋初始值
        created:function () {
            var _this = this;
            $.ajax({
                url:"/houtai/page/products/product/getSession",
                type:"post",
                dataType:"json",
                async: false,
                success:function (data) {
                    console.log(data);
                    if(data.message == "success"){
                        //把查询到的商品对象赋值给定义的product，用于渲染表单
                        _this.product = data.obj;
                        //给轮播图数组赋值，渲染原有的轮播图到页面
                        productImgHeads = data.obj.productImgHeads;
                        if(productImgHeads.length > 0){
                            for(var i = 0;i < productImgHeads.length;i++){
                                $("#head_img_prev").append('<img style="height: 150px;width: 150px;margin-right: 5px" src="'+ productImgHeads[i].productImgHeadUrl +'">');
                            }
                        };
                        //给商品详情图数组赋值，渲染原有的商品详情图到页面
                        productImgDetails = data.obj.productImgDetails;
                        if(productImgDetails.length > 0){
                            for(var i = 0;i < productImgDetails.length;i++){
                                $("#head_img_detail").append('<img style="height: 150px;width: 150px;margin-right: 5px" src="'+ productImgDetails[i].productImgDetailUrl +'">');
                            }
                        };
                        //把当前修改的商品ID赋值给全局商品ID
                        productId = data.obj.productId;
                    }else{
                        location.href = "/houtai/page/exception/500.html";
                    }
                }
            });
        }
    });

    //layui相关操作
    layui.use(['upload','jquery','laypage','laydate','form'], function() {
        var upload = layui.upload;
        var $ = layui.jquery;
        var laydate = layui.laydate;
        var form = layui.form;
        //刷新表单
        form.render();

        //验证表单内容
        form.verify({
            notNull:function (value, item) {
                if(value == null || value.trim() == ''){
                    return "内容不能为空";
                }
            },
            price:[
                /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
                '请填写正确的价格'
            ],
            num:[
                /(^[1-9]\d*$)/,
                '库存只能是正整数'
            ]
        });

        //点击图片放大，本页面放弃，改为点击图片删除
        window.showBigImage = function(e) {
            layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true, //点击阴影关闭
                area: [$(e).width + 'px', $(e).height + 'px'], //宽高
                content: "<img src=" + $(e).attr('src') + " />"
            });
        };

        // 获取当前点击元素
        // $(document).on('click','.layui-upload-img',function(){
        //     console.log("图片点击了");
        //     showBigImage($(this));
        // });


        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            ,url: '/houtai/page/products/product/uploadProductImg' //改成您自己的上传接口
            ,auto: false
            ,bindAction: '#upload'
            ,choose: function(obj){
                isChangeProductImg = true;
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
            }
            ,done: function(res){
                //如果上传失败
                if(res.code == 200){
                    var productImgHeadUrl = res.message.split("||")[0];
                    checkProductIsSure = true;
                    layer.msg('图片上传成功');
                    console.log(res.message);
                    $("#productImg").val(productImgHeadUrl);
                }else{
                    layer.msg('图片校验失败');
                }
            }
            ,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">图片校验失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
        });
        //判断是否未选择图片误点了确认按钮
        $("#upload").click(function () {
            if(!isChangeProductImg){
                layer.msg("还没有选择图片哦");
            }
        })

        // 轮播图多图片上传
        upload.render({
            elem: '#test2'
            ,url: '/houtai/page/products/product/uploadHeadImg' //改成您自己的上传接口
            ,multiple: true
            ,number:0
            ,auto: false
            ,bindAction: '#uploadHead'
            ,choose: function(obj){
                isChangeHead = true;
                $("#head_img_prev").attr("hidden",true);
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo2').append('<img style="width: 150px;height: 150px;margin-right: 5px" src="'+ result +'" alt="'+ file.name
                        +'" title="点击删除" class="layui-upload-img" onclick="delMultipleImgs(this)">')
                });
            }
            ,done: function(res){
                if(res.code == 200){
                    checkHeadIsSure = true;
                    layer.msg("轮播图上传成功")
                    console.log("res.message");
                    console.log(res.message);
                    var productImgHeadUrl = res.message.split("||")[0];
                    console.log(productImgHeadUrl);
                    if(isFirstHead == 1){
                        productImgHeads = [];
                        var product = {productId:productId,productImgHeadUrl:productImgHeadUrl,productImgHeadSort:res.message.split("||")[1]};
                        productImgHeads.push(product);
                        console.log(product);
                        isFirstHead++;
                        //追加图片成功追加文件名至图片容器
                        multiple_images.push(res.message.split("||")[0]);
                        $('#productImgHeads').val(multiple_images);
                    }else{
                        var product = {productId:productId,productImgHeadUrl:productImgHeadUrl,productImgHeadSort:res.message.split("||")[1]};
                        productImgHeads.push(product);
                        console.log(product);
                        //追加图片成功追加文件名至图片容器
                        layer.msg("轮播图上传成功");
                        multiple_images.push(productImgHeadUrl);
                        $('#productImgHeads').val(multiple_images);
                    }
                }
            }
        });
        //判断是否未选择图片误点了确认按钮
        $("#uploadHead").click(function () {
            if(!isChangeHead){
                layer.msg("还没有选择图片哦");
            }
        })

        // 商品详情图多图片上传
        upload.render({
            elem: '#test3'
            ,url: '/houtai/page/products/product/uploadDetailImg' //改成您自己的上传接口
            ,multiple: true
            ,number:0
            ,auto: false
            ,bindAction: '#uploadDetail'
            ,choose: function(obj){
                isChangeDetail = true;
                $("#head_img_detail").attr("hidden",true);
                //预读本地文件示例，不支持ie8，同时增加点击图片删除
                obj.preview(function(index, file, result){
                    $('#demo3').append('<img style="width: 150px;height: 150px;margin-right: 5px" src="'+ result +'" alt="'+ file.name
                        +'" title="点击删除" class="layui-upload-img" onclick="delMultipleImgs(this)">')
                });
            }
            //单个图片上传完成之后的方法
            ,done: function(res){
                //判断是否上传成功
                if(res.code == 200){
                    checkDetailIsSure = true;
                    layer.msg("商品详情图上传成功")
                    console.log("res.message");
                    console.log(res.message);
                    var productImgDetailUrl = res.message.split("||")[0];
                    console.log(productImgDetailUrl);
                    var productDetailSort = res.message.split("||")[1];
                    console.log(productDetailSort);
                    //判断是否是上传第一张图片，如果是第一章图片就把原轮播图数组清空，否则就添加数据进数组
                    if(isFirstDetail == 1){
                        productImgDetails = [];
                        var product = {productId:productId,productImgDetailUrl:productImgDetailUrl,productDetailDesc:1,productDetailSort:productDetailSort};
                        productImgDetails.push(product);
                        console.log(product);
                        isFirstDetail++;
                        //追加图片成功追加文件名至图片容器
                        multiple_images.push(productImgDetailUrl);
                        $('#productImgDetails').val(multiple_images);
                    }else{
                        var product = {productId:productId,productImgDetailUrl:productImgDetailUrl,productDetailDesc:1,productDetailSort:productDetailSort};
                        productImgDetails.push(product);
                        console.log(product);
                        //追加图片成功追加文件名至图片容器
                        layer.msg("商品详情图上传成功");
                        multiple_images.push(productImgDetailUrl);
                        $('#productImgDetails').val(multiple_images);
                    }
                }
            }
        });
        //判断是否未选择图片误点了确认按钮
        $("#uploadDetail").click(function () {
            if(!isChangeDetail){
                layer.msg("还没有选择图片哦");
            }
        })



        //监听表单提交，上述的submit()中的值为事件过滤器的值
        form.on('submit(updateSubmit)', function(data){
            console.log("提交表单了");
            //校验表单字段是否符合规则
            function checkNotNull(){
                var productName = $("#productName").val();
                var productDesc = $("#productDesc").val();
                var productType = $("#productType").val();
                var productStatus = $("input[name='productStatus']:checked").val();
                if(productName != null && productName.trim() != '' && productDesc != null && productDesc.trim() != "" && productType > 0 && productStatus >= 0){
                    return true;
                }else {
                    return false;
                }
            }
            function checkPrice(){
                var productPrice = $("#productPrice").val();
                var promotionPrice = $("#promotionPrice").val();
                if(!(/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(productPrice)) && !(/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(promotionPrice))){
                    return false;
                }else {
                    return true;
                }
            }
            function checkNum(){
                var productNum = $("#productNum").val();
                if(!(/(^[1-9]\d*$)/.test(productNum))){
                    return false;
                }else {
                    return true;
                }
            }
            if(checkNotNull() && checkPrice() && checkNum()){
                    var productName = $("#productName").val();
                    var productDesc = $("#productDesc").val();
                    var productType = $("#productType").val();
                    var productStatus = $("input[name='productStatus']:checked").val();
                    var productPrice = $("#productPrice").val();
                    var promotionPrice = $("#promotionPrice").val();
                    var productNum = $("#productNum").val();
                    var businessId = $("#businessId").val();
                    var productId = $("#productId").val();
                    var productCode = $("#productCode").val();
                    var productSales = $("#productSales").val();
                    var productImg = $("#productImg").val();
                    var productIshot = $("input[name='productIshot']:checked").val();
                    var product = {productName:productName,productDesc:productDesc,productType:productType,
                        productStatus:productStatus,productPrice:productPrice,promotionPrice:promotionPrice,
                        productNum:productNum, businessId:businessId,productId:productId,productCode:productCode,
                        productSales:productSales,productImg:productImg,productImgHeads:productImgHeads,
                        productImgDetails:productImgDetails,productIshot:productIshot};
                    console.log(product);
                    let s = JSON.stringify(product);
                    if(isChangeProductImg && !checkProductIsSure){
                       layer.msg("请先确认商品展示图再提交");
                    }else if(isChangeHead && !checkHeadIsSure){
                        layer.msg("请先确认商品轮播图再提交");
                    }else if(isChangeDetail && !checkDetailIsSure){
                        layer.msg("请先确认商品详情图再提交");
                    }else{
                        $.ajax({
                            url:"/houtai/page/products/product/sureUpdate",
                            data:s,
                            type:"post",
                            contentType:"application/json",
                            dataType:"json",
                            success:function (data) {
                                if(data.message == "success"){
                                    //恢复为初始值
                                    checkProductIsSure = false;
                                    checkHeadIsSure = false;
                                    checkDetailIsSure = false;
                                    isChangeProductImg = false;
                                    isChangeHead = false;
                                    isChangeDetail = false;
                                    layer.msg("修改成功");
                                    location.href = "/houtai/page/products/product/list.html";
                                }else if(data.message == "premissionException"){
                                    location.href = "/houtai/page/exception/NoPremission.html";
                                }else if(data.message == "serverException"){
                                    location.href = "/houtai/page/exception/500.html";
                                }else{
                                    layer.msg("修改失败", {icon: 5});
                                }
                            }
                        })
                    }
                }
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
    });

    //单击图片删除图片 【注册全局函数】
    function delMultipleImgs(this_img){
        //获取下标
        var subscript=$("#demo2 img").index(this_img);
        //删除图片
        this_img.remove();
        //删除数组
        multiple_images.splice(subscript, 1);
        //重新排序
        multiple_images.sort();
        $('.multiple_show_img').val(multiple_images);
        //console.log("multiple_images",multiple_images);
        //返回
        return ;
    }


</script>

</body>
</html>